/**
 *  实现一个LazyMan，可以按照以下方式调用: 两种答案 队列 异步promise
 *  
 *  LazyMan('Hank')输出:
 *  Hi! This is Hank!
 *  
 *  LazyMan('Hank').sleep(10).eat('dinner')输出
 *  Hi! This is Hank!
 *  //等待10秒..
 *  Wake up after 10
 *  Eat dinner~
 *  
 *  LazyMan('Hank').eat('dinner').eat('supper')输出
 *  Hi This is Hank!
 *  Eat dinner~
 *  Eat supper~
 *  
 *  LazyMan('Hank').sleepFirst(5).eat('supper')输出
 *  //等待5秒
 *  Wake up after 5
 *  Hi This is Hank!
 *  Eat supper
 */

function LazyMan(name) {
  if (!(this instanceof LazyMan)) {
    return new LazyMan(name);
  }
  const self = this;
  this.list = [
    Promise.resolve(console.log('Hi This is ' + name + '!'));
  ];

  this.fire = function f(arr) {
    const foo = arr.shift(arr);
    if (foo instanceof Promise) {
      foo.then(function(){
        if (arr.length > 0) {
          f(arr);
        }
      });
    }
  }

  setTimeout(function () {
    self.fire(self.list);
  }, 0);
}

LazyMan.prototype.sleep = function (time) {
  const sleep = new Promise (resolve) {
    setTimeout(function () {
      console.log('Wake up after ' + time);
      resolve();
    }, time * 1000);
  }
  this.list.push(sleep);
  return this;
}

LazyMan.prototype.eat = function (food) {
  // const dinner = function (cb) {
  //   console.log('Eat ' + food + '~');
  //   cb();
  // }
  const dinner = Promise.resolve(console.log('Eat ' + food + '~'));
  this.list.push(dinner);
  return this;
}

LazyMan.prototype.sleepFirst = function (time) {
  const sleepFirst = new Promise (resolve) {
    setTimeout(function () {
      console.log('Wake up after ' + time);
      resolve();
    }, time * 1000);
  }
  this.list.unshift(sleepFirst);
  return this;
}

LazyMan('Hank');


// LazyMan('Hank').sleep(1).eat('dinner');


// LazyMan('Hank').eat('dinner').eat('supper')

LazyMan('Hank').sleepFirst(1).eat('supper')